#include <utils/list.h>
#include <base.h>

list_node_t *list_next_node(list_node_t *node) {
	return node->next;
}

void list_append(list_node_t *head, list_node_t *node) {
	list_node_t *last_node = list_get_last_node(head);
	bool is_circular = last_node->next == head;

	last_node->next = node;

	if(is_circular) {
		list_get_last_node(node)->next = head;
	}
}

list_node_t *list_remove(list_node_t *head, list_node_t *node) {
	list_node_t *entry = head;
	list_node_t *prev = NULL;
	list_node_t *last = list_get_last_node(head);

	while(entry) {
		if(entry == node) {
			if(prev == NULL) {
				head = entry->next;
			} else {
				prev->next = entry->next;
			}

			return head;
		}

		if(entry == last) {
			return head;
		}

		prev = entry;
		entry = entry->next;
	}

	//	应该是跑不到这里的

	return head;
}

list_node_t *list_get_last_node(list_node_t *head) {
	list_node_t *entry = head;

	while(entry->next) {
		if(entry->next == head) {	 //	循环链表
			return entry;
		}

		entry = entry->next;
	}

	return entry;
}

void list_make_circular(list_node_t *head) {
	list_get_last_node(head)->next = head;
}